'use strict';

const BaseService = require('./base');
const modelName = 'Menu';
class RouterService extends BaseService {
  constructor(ctx) {
    super(ctx, modelName);
  }

  async allList(where,include) {
    const list = await this.ctx.model[this.modelName].findAll({
      where,
      order:[
        // id 降序
        ['sort','ASC'],
      ],
      raw: true
    });
    // 根据pid组装为树结构
    return this.listToTree(list);
  }
  /**
   * 将列表转换为树形结构
   * @param {Array} list 原始列表数据
   * @param {Object} config 配置项
   * @returns {Array} 树形结构数据
   */
  listToTree(list, config = {}) {
    const {
      idKey = 'id',         // id字段名
      pidKey = 'pid',       // 父id字段名
      childrenKey = 'children'  // 子节点字段名
    } = config

    const tree = []
    const map = {}

    // 先将数据转为Map存储
    list.forEach(item => {
      map[item[idKey]] = {
        ...item,
        value: item.id,
        label: item.name,
        [childrenKey]: []
      }
    })

    // 构建树形结构
    list.forEach(item => {
      const node = map[item[idKey]]
      const pid = item[pidKey]

      if (pid === 0 || pid === '0' || !pid) {
        // 根节点直接加入树中
        tree.push(node)
      } else {
        // 非根节点加入到父节点的children
        if (map[pid]) {
          map[pid][childrenKey].push(node)
        }
      }
    })

    return tree
  }
}


module.exports = RouterService;
